package com.lagou;

import com.lagou.rpc.ServerHandler;
import com.lagou.register.ZkUtil;
import com.lagou.rpc.*;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServerBootstrap implements ApplicationRunner {

    private static CuratorFramework zkClient;

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(ServerBootstrap.class, args);
    }

    //hostName:ip地址  port:端口号
    public void startServer(String hostName,int port)  {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            io.netty.bootstrap.ServerBootstrap serverBootstrap = new io.netty.bootstrap.ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //pipeline.addLast(new StringEncoder());
                            //pipeline.addLast(new StringDecoder());
                            pipeline.addLast( new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                            pipeline.addLast( new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                            pipeline.addLast(new ServerHandler());

                        }
                    });

            serverBootstrap.bind(hostName, port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void registServer(String ip, int port){
        zkClient = ZkUtil.getZkClient();
        try {
            ZkUtil.register(zkClient, ip, port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String ip = ZkUtil.getLocalIpv4Address();
        int port = 8991;

        //1.注册服务
        registServer(ip, port);

        //2.启动netty
        startServer(ip, port);
    }


}
